import requests
##cron: 7 7 * * *
##new Env("金价查询")
def get_gold_price():
    url = "https://apis.tianapi.com/gold/index"
    params = {
        'key': '81f94231ec7fabb001789aa365fb8d20',
        'kinds': 'au9999'
    }
    
    try:
        response = requests.get(url, params=params)
        response.raise_for_status()  # 检查请求是否成功
        return response.json()
    except requests.RequestException as e:
        print(f"发生错误: {e}")
        return None
def format_gold_price(data):
    if data and data['code'] == 200 and 'list' in data['result']:
        gold_info = data['result']['list'][0]
        
        # 根据价格波动添加不同的表情
        latest_price = float(gold_info['latestprice'])
        # 这里可以添加逻辑判断价格涨跌，暂时使用通用表情
        
        formatted_output = (
            f"💰「金价每日推送」💰\n\n"
            f"📈 最新价: {gold_info['latestprice']}元/克\n"
            f"🕒 更新时间: {gold_info['updatetime']}\n"
            f"📊 数据来源: 天行数据\n"
            f"✨ 投资有风险，入市需谨慎 ✨"
        )
        return formatted_output
    else:
        return "❌ 未找到有效的黄金价格数据。"
def push_to_wechat_bot(message, webhook_url):
    data = {
        "msgtype": "text",
        "text": {
            "content": message
        }
    }
    try:
        response = requests.post(webhook_url, json=data)
        response.raise_for_status()
        return response.json()
    except requests.RequestException as e:
        print(f"推送消息失败: {e}")
        return None
# 获取黄金价格信息
gold_price_data = get_gold_price()
# 格式化黄金价格信息
if gold_price_data:
    formatted_gold_price = format_gold_price(gold_price_data)
    print(formatted_gold_price)
    
    # 推送到企业微信机器人
    webhook_url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=c4ed66c7-ea68-4b51-be3f-8319beb4504d"
    push_to_wechat_bot(formatted_gold_price, webhook_url)
else:
    print("❌ 获取黄金价格数据失败。")